<template>
 <div>
    <h2 v-if="title">{{title}}</h2>
    <div id="bar" :class="className" :style="{height:height,width:width}" />
 </div>
</template>

<script>
import macarons from '@/assets/theme/macarons'
import { inject, onMounted, reactive, onUnmounted } from 'vue'
export default {
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    title: {
      type: String,
      default: ''
    },
     width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '350px'
    },
    autoResize: {
      type: Boolean,
      default: true
    },
    chartData: {
      type: Object,
      required: true
    }
  },
  setup(props) {
    let $echarts = inject('echarts')
    let xData = reactive([])
    let yData = reactive([])

    function setData() {
      xData = props.chartData.map( v => v.num)
      yData = props.chartData.map( v => v.title)
    }

    setData()

    onMounted(() => {
      let myChart = $echarts.init( document.getElementById('bar'), macarons)
      
      myChart.setOption({
        textStyle: {
          color: '#fff'
        },
        grid: {
          top: "3%",
          left: "1%",
          right: "6%",
          bottom: "3%",
          containLabel: true, // 包含坐标轴文字 包括了坐标轴标签在内的所有内容所形成的矩形的位置
        },
        xAxis: {
          type: 'value'
        },
        yAxis: {
          type: 'category',
          data: yData
        },
        tooltip: {
          trigger: "axis"
        },
        series: [
          {
            type: 'bar',
            data: xData,
            itemStyle: {
              // barBorderRadius: [0,20,20,0],
              borderRadius: [0,20,20,0], // （顺时针左上，右上，右下，左下）
              // 颜色渐变函数 右下左上 
              color: new $echarts.graphic.LinearGradient(0,0,1,0,[{
                offset: 0,
                color: '#005eaa'
              },
              {
                offset: 0.5,
                color: '#339ca8'
              }, {
                offset: 1,
                color: '#cda819'
              }])
            }
          }
        ]
      })

      window.addEventListener("resize", (() => {
        myChart.resize();
      }))
    })

    onUnmounted(() => {
      window.removeEventListener("resize")
    })

    return {
      
    }
  }
}
</script>

<style scoped>

</style>